<?php

/**
 *   OPENSHOP 管理中心管理员角色
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: acl_role.php,v 1.0 2009/06/17 08:36:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

$exc = new exchange($os->table('acl_role'), $db, 'role_id', 'role_name');

/*------------------------------------------------------ */
//-- 办事处列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
	//检查权限
	admin_priv(); 
    $smarty->assign('ur_here',      '管理员角色列表');
    $smarty->assign('action_link',  array('text' => '添加角色', 'href' => 'acl_role.php?act=add'));
    $smarty->assign('full_page',    1);

    $acl_role_list = get_acl_rolelist();
    $smarty->assign('acl_role_list',  $acl_role_list['role']);
    $smarty->assign('filter',         $acl_role_list['filter']);
    $smarty->assign('record_count',   $acl_role_list['record_count']);
    $smarty->assign('page_count',     $acl_role_list['page_count']);

    assign_query_info();
    $smarty->display("acl_role_list.tpl");    
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $acl_role_list = get_acl_rolelist();
    $smarty->assign('acl_role_list',  $acl_role_list['role']);
    $smarty->assign('filter',         $acl_role_list['filter']);
    $smarty->assign('record_count',   $acl_role_list['record_count']);
    $smarty->assign('page_count',     $acl_role_list['page_count']);
    
    make_json_result($smarty->fetch('acl_role_list.tpl'), '',
        array('filter' => $acl_role_list['filter'], 'page_count' => $acl_role_list['page_count']));
}

/*------------------------------------------------------ */
//-- 列表页编辑名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_role_name')
{
    check_authz_json('edit_acl_role');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

    /* 检查名称是否重复 */
    if ($exc->num("role_name", $name, $id) != 0)
    {
        make_json_error(sprintf('该管理员角色已存在，请您换一个名称', $name));
    }
    else
    {
        if ($exc->edit("role_name = '$name'", $id))
        {
            admin_log($name, 'edit', 'acl_role');
            clear_cache_files();
            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf('编辑管理员角色时出错，请您再试一次', $name));
        }
    }
}

/*------------------------------------------------------ */
//-- 列表页编辑订单差额
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_role_difference')
{
    check_authz_json('edit_acl_role');

    $id     	= intval($_POST['id']);
    $difference = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("role_difference = '$difference'", $id))
    {
        admin_log($difference, 'edit', 'acl_role');
        clear_cache_files();
        make_json_result(stripslashes($difference));
    }
    else
    {
        make_json_result(sprintf('编辑管理员角色时出错，请您再试一次', $difference));
    }
}

/*------------------------------------------------------ */
//-- 列表页编辑角色密码
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_role_password')
{
    check_authz_json('edit_acl_role');

    $id       = intval($_POST['id']);
    $password = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("role_password = '$password'", $id))
    {
        admin_log($password, 'edit', 'acl_role');
        clear_cache_files();
        make_json_result(stripslashes($password));
    }
    else
    {
        make_json_result(sprintf('编辑管理员角色时出错，请您再试一次', $password));
    }
}

/*------------------------------------------------------ */
//-- 删除角色
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('drop_acl_role');

    $id = intval($_GET['id']);
    $role_func_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('acl_role_func'). " WHERE role_id='$id'");    
    $user_role_count = $db->getOne('SELECT COUNT(*) FROM ' .$os->table('acl_role_user'). " WHERE role_id='$id'");
        
    $role_name = $exc->get_name($id);

    if($role_func_count==0 && $user_role_count==0){
	    /* 删除该颜色 */
	    if($exc->drop($id)){
		    /* 记日志 */
		    admin_log($role_name, 'remove', 'acl_role');	
	    }
    }else{
    	make_json_error('角色 '.$role_name .' 与用户、权限还有关联,您不能删除!');
    }



    /* 清除缓存 */
    clear_cache_files();

    $url = 'acl_role.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 检查权限 */
    admin_priv('drop_acl_role');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg('没有选择记录');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('acl_role') .
                    " WHERE role_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log('', 'batch_remove', 'acl_role');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除成功');
        }
    }
}

/*------------------------------------------------------ */
//-- 添加、编辑角色
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_acl_role' : 'edit_acl_role';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert' : 'update');

    /* 初始化、取得办事处信息 */
    if ($is_add)
    {
        $agency = array(
            'role_id'     => 0,
            'role_name'   => '',
            'role_desc'   => ''
        );
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = $_GET['id'];
        $sql = "SELECT * FROM " . $os->table('acl_role') . " WHERE role_id = '$id'";
        $acl_role = $db->getRow($sql);
        if (empty($acl_role))
        {
            sys_msg('role does not exist');
        }
    }


    $smarty->assign('acl_role', $acl_role);


    /* 显示模板 */
    if ($is_add)
    {
        $smarty->assign('ur_here', '添加管理员角色');
    }
    else
    {
        $smarty->assign('ur_here', '编辑管理员角色');
    }
    if ($is_add)
    {
        $href = 'acl_role.php?act=list';
    }
    else
    {
        $href = 'acl_role.php?act=list&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '管理员角色列表'));
    
    assign_query_info();
    
    $smarty->display("acl_role_info.tpl");     
}

/*------------------------------------------------------ */
//-- 提交添加、编辑角色
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert';
    $is_add ? admin_priv('add_acl_role') : admin_priv('edit_acl_role'); // 检查权限

    /* 提交值 */
    $acl_role = array(
        'role_id'     => intval($_POST['id']),
        'role_name'   => sub_str($_POST['role_name'], 255, false),
        'role_desc'   => $_POST['role_desc']
    );

    /* 判断名称是否重复 */
    if (!$exc->is_only('role_name', $acl_role['role_name'], $acl_role['role_id']))
    {
        sys_msg('该管理员角色已存在，请您换一个名称');
    }

    /* 保存办事处信息 */
    if ($is_add)
    {
        $db->autoExecute($os->table('acl_role'), $acl_role, 'INSERT');
        $acl_role['role_id'] = $db->insert_id();
    }
    else
    {
        $db->autoExecute($os->table('acl_role'), $acl_role, 'UPDATE', "role_id = '$acl_role[role_id]'");
    }

    /* 记日志 */
    if ($is_add)
    {
        admin_log($acl_role['role_name'], 'add', 'acl_role');
    }
    else
    {
        admin_log($acl_role['role_name'], 'edit', 'acl_role');
    }

    /* 清除缓存 */
    clear_cache_files();

    /* 提示信息 */
    if ($is_add)
    {
        $links = array(
            array('href' => 'acl_role.php?act=add', 'text' => '继续添加新的角色'),
            array('href' => 'acl_role.php?act=list', 'text' => '返回管理员角色列表')
        );
        sys_msg('添加管理员角色成功', 0, $links);
    }
    else
    {
        $links = array(
            array('href' => 'acl_role.php?act=list&' . list_link_postfix(), 'text' => '返回管理员角色列表')
        );
        sys_msg('编辑管理员角色成功', 0, $links);
    }
}elseif($_REQUEST['act']=='list_user'){
	
	admin_priv('view_acl_role_user');
	
    $smarty->assign('ur_here',      '用户列表');
    $smarty->assign('action_link',  array('text' => '添加用户', 'href' => 'acl_role.php?act=add_user&role_id='.intval($_GET['role_id'])));
    $smarty->assign('full_page',    1);

    $list = get_acl_role_userlist();
    $smarty->assign('role_user_list', $list['role_user']);
    $smarty->assign('filter',         $list['filter']);
    $smarty->assign('record_count',   $list['record_count']);
    $smarty->assign('page_count',     $list['page_count']);

    assign_query_info();
    
    $smarty->display("acl_role_user_list.tpl");    
}elseif($_REQUEST['act']=='query_user'){
    $list = get_acl_role_userlist();
    $smarty->assign('role_user_list', $list['role_user']);
    $smarty->assign('filter',         $list['filter']);
    $smarty->assign('record_count',   $list['record_count']);
    $smarty->assign('page_count',     $list['page_count']);
    
    make_json_result($smarty->fetch('acl_role_user_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  
}elseif($_REQUEST['act']=='remove_user'){
	
    check_authz_json('drop_acl_role_user');

    $user_id = intval($_GET['id']);
    $role_id = intval($_GET['role_id']);
    $user_name = $db->getOne("SELECT user_name FROM " . $os->table('admin_user') . " WHERE user_id='$user_id'");    
    if($db->query("DELETE FROM " . $os->table('acl_role_user') . " WHERE role_id='$role_id' AND user_id='$user_id'")){
	    /* 记日志 */
	    admin_log($user_name, 'remove', 'acl_role_user');	
    }

    /* 清除缓存 */
    clear_cache_files();

    $url = 'acl_role.php?act=query_user&' . str_replace('act=remove_user', '', $_SERVER['QUERY_STRING']);

    os_header("Location: $url\n");
    exit;	
}
/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_user')
{
    /* 检查权限 */
    admin_priv('drop_acl_role_user');
    
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']) || empty($_GET['role_id']))
    {
        sys_msg('没有选择记录');
    }
    else
    {
        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            /* 删除记录 */
            $sql = "DELETE FROM " . $os->table('acl_role_user') . " WHERE role_id=".intval($_GET['role_id']).
                   " AND user_id " . db_create_in($ids);
            $db->query($sql);

            /* 记日志 */
            admin_log('', 'batch_remove', 'acl_role_user');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg('批量删除成功');
        }
    }
}elseif($_REQUEST['act']=='add_user'){

    /* 检查权限 */
    admin_priv('add_acl_role_user');
	
	if(empty($_GET['role_id'])){
		sys_msg('invalid param');
	}

    $smarty->assign('ur_here',      '添加用户');
    $smarty->assign('action_link',  array('text' => '用户列表', 'href' => 'acl_role.php?act=list_user&role_id='.intval($_GET['role_id'])));
    
	$role_id = intval($_GET['role_id']);
 	$acl_role = $db->getRow("SELECT role_id,role_name FROM " . $os->table('acl_role') . " WHERE role_id='$role_id'");  	

    $user_list = $db->getAll("SELECT a_u.user_id,a_u.user_name FROM " . $os->table('admin_user') . " a_u LEFT JOIN " . 
                       $os->table('acl_role_user') . " r_u ON r_u.user_id=a_u.user_id WHERE r_u.role_id='$role_id'");
 	$acl_role['user_list'] = $user_list;
 	
 	$smarty->assign('acl_role', $acl_role);
 	
    assign_query_info();
    $smarty->display("acl_role_user_info.tpl");   
}elseif($_REQUEST['act'] == 'get_users_list'){
	
	check_authz_json('add_acl_role_user');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = $db->getAll("SELECT user_id,user_name FROM " . $os->table('admin_user') . " WHERE action_list!='all' AND user_name LIKE '%" . 
                json_str_iconv($filters->keyword)."%' OR email LIKE '%" . json_str_iconv($filters->keyword)."%'");    
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value' => $val['user_id'],
                       'text'  => $val['user_name'],
                       'data'  => '');
    }

    make_json_result($opt);
}elseif($_REQUEST['act'] == 'add_role_user'){
	
	check_authz_json('add_acl_role_user');
	
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $json = new JSON;
    $fittings   = $json->decode($_GET['add_ids']);	
    $arguments  = $json->decode($_GET['JSON']);
    $role_id   = $arguments[0];
    
	foreach($fittings as $val){
		$super_row = $db->getRow("SELECT user_name,action_list FROM " . $os->table('admin_user') . " WHERE user_id='$val'");
		if(!empty($super_row['action_list']) && trim($super_row['action_list'])=='all'){
			make_json_error('管理员 ' . $super_row['user_name'] . ' 是系统超级管理员,您不能添加!');			
		}
     	$sql = "INSERT INTO " . $os->table('acl_role_user') . " (role_id, user_id) " .
                "VALUES ('$role_id', '$val')";
        $db->query($sql, 'SILENT');		
	}
    
    $arr = $db->getAll("SELECT a_u.user_id,a_u.user_name FROM " . $os->table('acl_role_user') . " r_u LEFT JOIN " . 
                       $os->table('admin_user') . " a_u ON r_u.user_id=a_u.user_id WHERE r_u.role_id='$role_id'");
    
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['user_id'],
                       'text'       => $val['user_name'],
                       'data'       => '');
    }

    clear_cache_files();
    make_json_result($opt);  	
}elseif($_REQUEST['act']=='drop_role_user'){
	
    check_authz_json('drop_acl_role_user');
    
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    $fittings   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
	$role_id   = $arguments[0];

    $sql = "DELETE FROM " .$os->table('acl_role_user') .
            " WHERE role_id='$role_id' AND " .db_create_in($fittings, 'user_id');
    $db->query($sql);

    $arr = $db->getAll("SELECT a_u.user_id,a_u.user_name FROM " . $os->table('acl_role_user') . " r_u LEFT JOIN " . 
                       $os->table('admin_user') . " a_u ON r_u.user_id=a_u.user_id WHERE r_u.role_id='$role_id'");
                       
    $opt = array();

    foreach ($arr AS $val)
    {
        $opt[] = array('value'      => $val['user_id'],
                        'text'      => $val['user_name'],
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($opt);
}elseif($_REQUEST['act']=='allot'){
	
    admin_priv('allot_acl_role');
    
    $role_id = intval($_GET['id']);
    /* 获得该管理员的权限 */
    $purview_arr = $db->getAll("SELECT action_id FROM " .$os->table('acl_role_func'). " WHERE role_id = '$role_id'");
    $privilege_arr = array();
	while (list($key, $val) = each($purview_arr)) {
	    array_push($privilege_arr, $val['action_id']);
	}

    /* 获取权限的分组数据 */
    $sql_query = "SELECT action_id, parent_id, type, action_name, action_code, sort_order, cid FROM " .$os->table('acl_action').
                 " WHERE type='group' AND parent_id = 0";
    $res = $db->query($sql_query);
    while ($rows = $db->FetchRow($res))
    {
        $priv_arr[$rows['action_id']] = $rows;
    }

    /* 按权限组查询底级的权限名称 */
    $sql = "SELECT action_id, parent_id, type, action_name, action_code, sort_order, cid FROM " .$os->table('acl_action').
           " WHERE type='url' AND parent_id " .db_create_in(array_keys($priv_arr));
    $result = $db->query($sql);
    while ($priv = $db->FetchRow($result))
    {
        $priv_arr[$priv["parent_id"]]["priv"][$priv["action_id"]] = $priv;
	    $sql_leaf = "SELECT action_id, parent_id, type, action_name, action_code, sort_order, cid FROM " .$os->table('acl_action').
	           " WHERE type='act' AND parent_id =" .intval($priv["action_id"]);
	    $result_leaf = $db->query($sql_leaf);
	    $priv_leaf_arr = array();
	    while ($priv_leaf = $db->FetchRow($result_leaf))
	    {
	        $priv_leaf_arr[$priv_leaf["action_id"]] = $priv_leaf;
	    } 
	    if(!empty($priv_leaf_arr) && is_array($priv_leaf_arr)){
	    	$priv_arr[$priv["parent_id"]]["priv"][$priv["action_id"]]["priv"] = $priv_leaf_arr;    
	    }
    }
    

    foreach ($priv_arr AS $action_id => $action_group)
    {
    	$priv_arr[$action_id]['cando'] = (in_array($action_group['action_id'],$privilege_arr) === true || $priv_str == 'all') ? 1 : 0;
    	if(isset($action_group['priv']) && is_array($action_group['priv'])){
            $priv_arr[$action_id]['priv_list'] = join(',', array_keys($action_group['priv']));
	        foreach ($action_group['priv'] AS $key => $val)
	        {
	            $priv_arr[$action_id]['priv'][$key]['cando'] = (in_array($val['action_id'],$privilege_arr) === true || $priv_str == 'all') ? 1 : 0;
	            if(isset($val['priv']) && is_array($val['priv'])){
	            	$priv_arr[$action_id]['priv'][$key]['priv_list'] = join(',', array_keys($val['priv']));
	            	foreach($val['priv'] AS $leaf_key => $leaf_val){
	            		$priv_arr[$action_id]['priv'][$key]['priv'][$leaf_key]['cando'] = (in_array($leaf_val['action_id'],$privilege_arr) === true || $priv_str == 'all') ? 1 : 0;
	            	}
	            	$priv_arr[$action_id]['priv_list'] .= ','.$priv_arr[$action_id]['priv'][$key]['priv_list'];
	            }
	        }
    	}
    }
    
    $acl_role = $db->getRow("SELECT role_name,role_id FROM " . $os->table('acl_role') . " WHERE role_id=" . intval($_GET['id']));
    /* 赋值 */
    $smarty->assign('ur_here',     '分派角色权限' . ' [ '. $acl_role['role_name'] . ' ] ');
    $smarty->assign('action_link', array('href'=>'acl_role.php?act=list', 'text' => '管理员角色列表'));
    $smarty->assign('priv_arr',    $priv_arr);
    $smarty->assign('form_act',    'update_allot');
    $smarty->assign('role_id',     $acl_role['role_id']);

    /* 显示页面 */
    assign_query_info();
    
    $smarty->display("acl_role_allot.tpl");    	
}elseif ($_REQUEST['act'] == 'update_allot'){
	
    admin_priv('allot_acl_role');
    
  //  echo '2 ' . microtime() . "<br>\n";
    
    $role_id = intval($_POST['id']);
    $role_name = $db->getOne("SELECT role_name FROM " . $os->table('acl_role') . " WHERE role_id = '$role_id'");
    $db->query("DELETE FROM " . $os->table('acl_role_func') . " WHERE role_id='$role_id'");
   
   // echo '3 ' . microtime() . "<br>\n";
    
    /* 更新管理员的权限 */
    $i = 1;
    $insert_sql = "INSERT INTO " . $os->table('acl_role_func') . " (action_id,role_id) VALUES ";
    if(!empty($_POST['action_id'])){
	    foreach ($_POST['action_id'] as $action_id){
	    	$i++;
	    	$insert_sql .= " ('{$action_id}','{$role_id}'),";
	    	//if($i > 2) break;
	    	//$db->query("INSERT INTO " . $os->table('acl_role_func') . "(action_id,role_id) VALUES('$action_id','$role_id')");
	    	//echo microtime(). "<br>\n";
	    }
	    $insert_sql = preg_replace("/,$/",'',$insert_sql);
	    //$db->query("INSERT INTO `uip`.`open_acl_role_func` (action_id,role_id) VALUES (1,25),(26,25) ");
	    $db->query($insert_sql);
    }
    
   // echo '4 ' . microtime(). "<br>\n";
   // exit;
    
    /* 动态更新管理员的SESSION */    
    $privilege_arr = $db->getAll("SELECT r_f.action_id FROM " . $os->table('acl_role_user') . " r_u LEFT JOIN" . $os->table('acl_role_func') . 
                        " r_f ON r_u.role_id=r_f.role_id WHERE r_u.role_id='$role_id' AND r_u.user_id=".$_SESSION["admin_id"]);
    if($privilege_arr){
	    $act_list = array();
		while (list($key, $val) = each($privilege_arr)) {
		    array_push($act_list, $val['action_id']);
		}
        $_SESSION["action_list"] = join(',', $act_list);
    }

    /* 记录管理员操作 */
    admin_log(addslashes($role_name), 'edit', 'privilege');

    /* 提示信息 */
    $link[] = array('text' => '管理员角色列表', 'href'=>'acl_role.php?act=list');
    sys_msg('编辑&nbsp;' . $role_name . '&nbsp;操作成功!', 0, $link);
}

/**
 * 取得管理员角色列表
 * @return  array
 */
function get_acl_rolelist()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'role_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('acl_role');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT * FROM " . $GLOBALS['os']->table('acl_role') . " ORDER BY $filter[sort_by] $filter[sort_order]";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
    	if (empty($rows['role_password'])) { $rows['role_password'] = '-'; }
        $arr[] = $rows;
    }

    return array('role' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
}

function get_acl_role_userlist(){
    $result = get_filter();
    if ($result === false)
    {
        /* 初始化分页参数 */
        $filter = array();
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'user_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
		$filter['role_id'] = empty($_REQUEST['role_id']) ? 0 : intval($_REQUEST['role_id']);
		
        /* 查询记录总数，计算分页数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['os']->table('admin_user') . " a_u LEFT JOIN " . 
               $GLOBALS['os']->table('acl_role_user') . " r_u ON r_u.user_id = a_u.user_id WHERE r_u.role_id=$filter[role_id]";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
        $filter = page_and_size($filter);

        /* 查询记录 */
        $sql = "SELECT r_u.role_id,a_u.user_id,a_u.user_name FROM " . $GLOBALS['os']->table('admin_user') . " a_u LEFT JOIN " . 
               $GLOBALS['os']->table('acl_role_user') . " r_u ON r_u.user_id = a_u.user_id WHERE r_u.role_id=$filter[role_id] ".
               " ORDER BY a_u.$filter[sort_by] $filter[sort_order]";
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $arr = array();
    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $arr[] = $rows;
    }

    return array('role_user' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}
?>